<?php
/**
 * Date: 2018/2/5
 * Time: 11:31
 * Author: zeronlee
 */

namespace App\Models\Orders;
use App\Models\Goods;
use App\Models\User\UserAddress;
use App\Models\User\Users;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Orders\Traits\Relationship\OrderRelationship;
use Illuminate\Support\Facades\Auth;

class Order extends Model
{

    use softDeletes,OrderRelationship;

    protected $table = 'orders';

    protected $primaryKey = 'id';

    public $timestamps = true;

    protected $guarded = ['column'];

    protected $fillable = ['id','sn','goods_id','consignee','payed','total','status','num','user_id'];

    protected $dates = ['delete_at'];

    public $status = [0=>'待支付',1=>'待发货',2=>'待收货',3=>'待评价',4=>'已关闭'];

    //待发货
    const PENDING = 1;

    /**
     * @param $filed
     * @param $where
     * @param $relate
     * @param $limit
     * @return mixed
     */
    public function lists($filed,$where,$relate,$limit){
        return $this->select($filed)
            ->where($where)
            ->leftJoin($relate['table'], function ($join) use ($relate){
                $join->on($relate['relation']);
            })->offset($limit['start'])
            ->orderBy('created_at','desc')
            ->limit($limit['length'])->get();
    }
    /**
     * 插入记录
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function insertRow($data){
        //构造入库数据
        //订单号
        $data['sn'] = $this->generateSn();

        //虚拟币交易 默认待发货
        $data['status'] = self::PENDING;
        //金币不足
        //安全矫正二次判断
        $reward = Users::where(['id'=>$data['user_id']])->value('reward');
        if ($data['payed'] > $reward) {

            throw new \Exception('金币不足');
        }
        $data['total'] = $data['payed'];
        $order = $this->create($data);
        if ($order->id > 0) {

            //返回当前订单信息
            return $order;

        }

        throw new \Exception('添加失败');

    }
    /**
     * 获取一条
     * @param mixed $request
     * @return mixed
     */
    public function getRow ($request){

        $where = ['orders.user_id' => $request->user_id];
        $field = ['orders.id','orders.sn','goods.name as goods_name','orders.num','orders.payed','orders.created_at','orders.consignee'];
        if ($request->id){
            $where['orders.id'] = $request->id;
        }
        return $this->select($field)->leftJoin('goods', function ($join) {
            $join->on('goods.id','=','orders.goods_id');
        })->where($where)->orderBy('created_at','desc')->first();

    }
    /**
     * 获取总条数
     * @param mixed $where
     * @return int
     */
    public function getCount ($where){

        $count = $this->where($where)->count();

        return $count;
    }
    /**
     * 生成订单号算法
     * @return string
     */
    private function generateSn () {
        $userId = Auth::user() ? Auth::user()->id : 0;
        $sn = 'SN'.$userId . date('Ymd',time()) . mt_rand(0,9999);

        return $sn;
    }
}